import { LLMAdapter, ModelInfo, ValidationResult, ValidationErrorCode } from '../../types/index';

export class OpenAIAdapter implements LLMAdapter {
  private readonly timeout = 10000; // 10秒超时

  async fetchModels(baseURL = 'https://api.openai.com/v1', apiKey?: string): Promise<ModelInfo[]> {
    try {
      const modelsUrl = `${baseURL}/models`;
      const response = await this.makeRequest(modelsUrl, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${apiKey || 'dummy'}`, // 使用提供的apiKey或假token
        },
      });

      if (response.ok) {
        const data = await response.json();
        return this.parseModels(data.data || []);
      } else {
        // 如果API调用失败，返回静态模型列表
        return this.getStaticModels();
      }
    } catch (error) {
      console.warn('Failed to fetch OpenAI models from', baseURL, ':', error);
      return this.getStaticModels();
    }
  }

  async validateApiKey(apiKey: string, baseURL = 'https://api.openai.com/v1'): Promise<ValidationResult> {
    if (!apiKey || !apiKey.trim()) {
      return {
        isValid: false,
        error: {
          code: ValidationErrorCode.INVALID_API_KEY,
          message: 'API Key 不能为空',
          suggestion: '请输入有效的 OpenAI API Key'
        }
      };
    }

    try {
      // 使用轻量级请求测试API Key
      const testPayload = {
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: 'test' }],
        max_tokens: 1
      };

      const response = await this.makeRequest(`${baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(testPayload),
      });

      if (response.ok) {
        const data = await response.json();
        return {
          isValid: true,
          metadata: {
            model: data.model,
            usage: data.usage
          }
        };
      } else {
        const errorData = await response.json().catch(() => ({}));
        return this.handleErrorResponse(response.status, errorData);
      }
    } catch (error) {
      return this.handleNetworkError(error);
    }
  }

  private async makeRequest(url: string, options: RequestInit): Promise<Response> {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);

    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      return response;
    } catch (error) {
      clearTimeout(timeoutId);
      throw error;
    }
  }

  private parseModels(models: any[]): ModelInfo[] {
    return models
      .filter(model => model.id && typeof model.id === 'string')
      .map(model => ({
        id: model.id,
        name: model.id,
        provider: 'openai',
        description: model.description || `OpenAI ${model.id} model`,
        contextLength: this.getContextLength(model.id),
        capabilities: this.getCapabilities(model.id),
      }));
  }

  private getContextLength(modelId: string): number {
    const contextMap: { [key: string]: number } = {
      'gpt-4': 8192,
      'gpt-4-32k': 32768,
      'gpt-4-turbo': 128000,
      'gpt-4o': 128000,
      'gpt-4o-mini': 128000,
      'gpt-3.5-turbo': 4096,
      'gpt-3.5-turbo-16k': 16384,
    };

    for (const [pattern, length] of Object.entries(contextMap)) {
      if (modelId.includes(pattern)) {
        return length;
      }
    }

    return 4096; // 默认值
  }

  private getCapabilities(modelId: string): string[] {
    const capabilities = ['text'];
    
    if (modelId.includes('gpt-4')) {
      capabilities.push('advanced-reasoning');
    }
    
    if (modelId.includes('vision') || modelId.includes('4o')) {
      capabilities.push('vision');
    }

    return capabilities;
  }

  private getStaticModels(): ModelInfo[] {
    return [
      {
        id: 'gpt-4o',
        name: 'GPT-4o',
        provider: 'openai',
        description: 'Most advanced GPT-4 model with vision capabilities',
        contextLength: 128000,
        capabilities: ['text', 'vision', 'advanced-reasoning'],
      },
      {
        id: 'gpt-4o-mini',
        name: 'GPT-4o mini',
        provider: 'openai',
        description: 'Faster and cheaper GPT-4o model',
        contextLength: 128000,
        capabilities: ['text', 'vision'],
      },
      {
        id: 'gpt-4-turbo',
        name: 'GPT-4 Turbo',
        provider: 'openai',
        description: 'Latest GPT-4 model with improved performance',
        contextLength: 128000,
        capabilities: ['text', 'advanced-reasoning'],
      },
      {
        id: 'gpt-4',
        name: 'GPT-4',
        provider: 'openai',
        description: 'High-intelligence flagship model',
        contextLength: 8192,
        capabilities: ['text', 'advanced-reasoning'],
      },
      {
        id: 'gpt-3.5-turbo',
        name: 'GPT-3.5 Turbo',
        provider: 'openai',
        description: 'Fast and efficient model for most tasks',
        contextLength: 4096,
        capabilities: ['text'],
      },
    ];
  }

  private handleErrorResponse(status: number, errorData: any): ValidationResult {
    switch (status) {
      case 401:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.INVALID_API_KEY,
            message: 'API Key 无效或已过期',
            suggestion: '请检查 API Key 是否正确，并确认账户状态正常'
          }
        };
      case 403:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.INSUFFICIENT_PERMISSIONS,
            message: '权限不足或账户被限制',
            suggestion: '请检查账户状态和 API 使用权限'
          }
        };
      case 429:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.RATE_LIMITED,
            message: '请求频率过高',
            suggestion: '请降低请求频率或升级账户计划'
          }
        };
      case 500:
      case 502:
      case 503:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.SERVER_ERROR,
            message: 'OpenAI 服务器错误',
            suggestion: '请稍后重试'
          }
        };
      default:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.UNKNOWN_ERROR,
            message: errorData.error?.message || '未知错误',
            suggestion: '请检查配置并重试'
          }
        };
    }
  }

  private handleNetworkError(error: any): ValidationResult {
    if (error.name === 'AbortError') {
      return {
        isValid: false,
        error: {
          code: ValidationErrorCode.TIMEOUT,
          message: '请求超时',
          suggestion: '请检查网络连接或稍后重试'
        }
      };
    }

    return {
      isValid: false,
      error: {
        code: ValidationErrorCode.NETWORK_ERROR,
        message: '网络连接错误',
        suggestion: '请检查网络连接并重试'
      }
    };
  }
}